﻿using System;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using DiscogsLib.Model;
using DiscogsLib.Shared;

namespace DiscogsLib.Client
{
    public class DiscogsLibClient
    {
        private HttpClient client;

        private JsonMediaTypeFormatter formatter;

        public DiscogsLibClient()
        {
            ConfigureClient();
        }

        private void ConfigureClient()
        {
            client = new HttpClient {BaseAddress = new Uri("http://api.discogs.com")};
            client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "DiscogsLibClient/1.0 +http://discogslib.codeplex.com");

            formatter = new JsonMediaTypeFormatter();
            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
        }

        public async Task<Master> GetMaster(ulong id)
        {
            var response = await client.GetAsync(String.Format("/masters/{0}", id));

            return await response.Content.ReadAsAsync<Master>(new[] {formatter});
        }

        public async Task<SearchResult> Search(string query, SearchType searchType, Format searchFormat)
        {
            string type = Enum.GetName(typeof (SearchType), searchType).ToLower();
            string format = Enum.GetName(typeof (Format), searchFormat).ToLower();
            var response = await client.GetAsync(String.Format("/database/search?q={0}&type={1}&format={2}", query, type, format));
            return await response.Content.ReadAsAsync<SearchResult>(new[] { formatter });
        }

    }
}
